package ru.usu.gv.gui.actions;

import ru.usu.gv.gui.GUIEngine;
import ru.usu.gv.gui.GUIUtilities;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.border.LineBorder;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Window;

/**
 * @author spupyrev
 * 13.11.2008
 */
public abstract class LongAction extends ActionBase
{
	private String message;

	public LongAction(String waitMessage)
	{
		message = waitMessage;
	}

	protected abstract void runAction();

	@Override
	public final void execute()
	{
		final Window window = showModalWindow();

		new Thread()
		{
			@Override
			public void run()
			{
				try
				{
					runAction();
				}
				finally
				{
					window.dispose();
				}
			}
		}.start();

		window.setVisible(true);
	}

	private JDialog showModalWindow()
	{
		final JFrame mainFrame = GUIEngine.getInstance().getMainFrame();
		JDialog dialog = new JDialog(mainFrame);

		JProgressBar progressBar = new JProgressBar(0, 100);
		progressBar.setString(message);
		progressBar.setBorder(new LineBorder(Color.blue, 3));
		progressBar.setStringPainted(true);
		int barWidth = 300;
		int barHeight = 30;
		progressBar.setPreferredSize(new Dimension(barWidth, barHeight));
		progressBar.setIndeterminate(true);
		progressBar.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

		dialog.add(progressBar);
		dialog.setModal(true);
		dialog.setUndecorated(true);
		dialog.pack();
		GUIUtilities.centralizeFrame(dialog);

		return dialog;
	}

}
